'use strict'

import store from '../store/index'


import { Message } from 'element-ui';

const API_URL = '/api/admin'
const H5_URL = 'http://localhost:8010';
// const API_URL = 'http://admin.diqwl.com/dshop/admin'
// const H5_URL = 'http://admin.diqwl.com/dshopH5';


const ATTR_API_CODE = 'status_code';
const ATTR_API_MSG = 'status_msg';


/**
* 获取、判断API返回状态
* code：200 请求成功；300 请求失败，发生异常；301 会话失效；302 没有访问权限；404 内容不见了
**/
function isSuccess(json){
	return getStatusCode(json) == 200;
}

function isFail(json){
	return getStatusCode(json) != 200;
}

function isSessionTimeOut(json){
	return getStatusCode(json) == 301;
}

function getStatusCode(json) {
	return json[ATTR_API_CODE];
}

function getStatusMsg(json) {
	return json[ATTR_API_MSG];
}

/**
* 用户调用API令牌
**/
function getApiToken(){
	return store.state.user.apiToken;
	//return "xxxx";
}

function getApiUserId(){
	return store.state.user.apiUserId;
	//return 1;
}


/**
* 消息提示：成功消息、失败消息
**/
function successTip(msg){
	
	if (msg == undefined || msg == null || msg == '') {
		return;
	}

	Message({
		type: 'success',
		message: msg,
		center: true
	});
}

function errorTip(msg){
	
	if (msg == undefined || msg == null || msg == '') {
		return;
	}

	Message({
		type: 'error',
		message: msg,
		center: true
	});
}

function apiSuccessTip(json){
	successTip(getStatusMsg(json));
}

function apiErrorTip(json){
	errorTip(getStatusMsg(json));
}


/**
* API回调
**/
function getDataCB(json, callback){
	if (isSuccess(json)) {
		if (callback != undefined) {
			callback(json);
		}
		apiSuccessTip(json);
		return;
	}
	apiErrorTip(json);

	if (isSessionTimeOut(json)) {
		setTimeout(function(){
			location.href = H5_URL + '/#/login/sto';
		}, 500);	
	}
}

function deleteCB(){

}

function addCB(){

}


function isLogin(){
	let apiToken = getApiToken();
	let userId = getApiUserId();

	if (apiToken && apiToken != '' && apiToken != 'undefined' 
		&& userId && userId != '' && userId != 'undefined' && userId > 0) {
		return true;
	}
	return false;
}

export default{
	isSuccess, isFail,
	getStatusMsg, 
	getApiUserId, getApiToken, isLogin,
	successTip, errorTip, apiSuccessTip, apiErrorTip, 
	getDataCB, deleteCB, addCB, 
	API_URL
}